import { defineStore } from 'pinia'
import { ref, reactive, watch } from 'vue'
import { stageList } from '@/config/stage'
import { useRoute } from 'vue-router'

export const useRouteStore = defineStore('route', () => {
  const route = useRoute()
  const stageLists = reactive(stageList)
  const sideBarList = reactive(stageList)
  const breadcrumbList = reactive([])
  const defaultActive = ref(route.path)

  const getBreadcrumbList = () => {
    defaultActive.value = route.path
    breadcrumbList.length = 0
    breadcrumbList.push(...deepBreadcrumb(sideBarList, route.path))
  }

  const deepBreadcrumb = (list, currentPath) => {
    for (let i = 0; i < list.length; i++) {
      const route = list[i]
      const path = route.path
      if (path === currentPath) {
        return [{ path, name: route.name, meta: route.meta }]
      }
      if (route.children && route.children.length) {
        const result = deepBreadcrumb(route.children, currentPath)
        const parentPath = currentPath.substring(0, currentPath.lastIndexOf('/'))
        if (parentPath === route.path && route.component) {
          defaultActive.value = route.path
        }
        if (result) {
          return [{ path, name: route.name, meta: route.meta }, ...result]
        }
      }
    }
    return null
  }

  watch(
    () => route.path,
    () => {
      getBreadcrumbList()
    },
    { immediate: true }
  )

  return {
    stageLists,
    sideBarList,
    defaultActive,
    breadcrumbList
  }
})
